package cn.edu.swu.hh;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

public class FileUtils {

    public static String saveImage(String urlStr, String savePath) {
        HttpURLConnection connection = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(true);
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(30000);
            connection.connect();

            int code = connection.getResponseCode();
            if (code / 100 == 3) {
                String loc = connection.getHeaderField("Location");
                if (loc != null && !loc.isEmpty()) {
                    return saveImage(loc, savePath);
                }
            }
            if (code != HttpURLConnection.HTTP_OK) {
                System.out.println("HTTP响应异常：" + code);
                return null;
            }

            in = connection.getInputStream();

            Path target = Paths.get(savePath);
            ensureDirectoryExists(target.getParent() == null ? null : target.getParent().toString());

            out = Files.newOutputStream(target, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

            byte[] buf = new byte[8192];
            int n;
            while ((n = in.read(buf)) != -1) {
                out.write(buf, 0, n);
            }
            out.flush();
            return target.toAbsolutePath().toString();
        } catch (Exception e) {
            System.out.println("下载出错：" + e.getMessage());
            return null;
        } finally {
            try { if (out != null) out.close(); } catch (IOException ignored) {}
            try { if (in  != null) in.close();  } catch (IOException ignored) {}
            if (connection != null) connection.disconnect();
        }
    }

    public static void ensureDirectoryExists(String dirPath) {
        if (dirPath == null || dirPath.isEmpty()) return;
        try {
            Path dir = Paths.get(dirPath);
            if (!Files.exists(dir)) Files.createDirectories(dir);
        } catch (IOException e) {
            System.out.println("创建目录失败：" + e.getMessage());
        }
    }

    //关键修复：为日志文件创建“父目录”，并使用 CREATE+APPEND
    public static void appendLog(String logFile, String line) {
        Path path = Paths.get(logFile).toAbsolutePath();
        try {
            Path parent = path.getParent();
            if (parent != null) Files.createDirectories(parent); //创建父目录（不是文件本身）
            Files.write(
                    path,
                    (line + System.lineSeparator()).getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE,   //首次写入时创建文件
                    StandardOpenOption.APPEND    //以后追加
            );
        } catch (IOException e) {
            System.out.println("写入日志失败：" + e.getMessage());
            System.out.println("日志绝对路径：" + path);
        }
    }
}